package com.ivan.stu.notetool.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ScreenUtils;
import com.google.gson.Gson;
import com.ivan.stu.notetool.ImageEdit.IMGEditActivity;
import com.ivan.stu.notetool.R;
import com.ivan.stu.notetool.View.LoadDialog;
import com.ivan.stu.notetool.View.Loading_view;
import com.ivan.stu.notetool.adapter.NoteSubjectAdapter;
import com.ivan.stu.notetool.callback.NegativeCallBack;
import com.ivan.stu.notetool.callback.PositiveCallBack;
import com.ivan.stu.notetool.model.MySubjectBean;
import com.ivan.stu.notetool.model.NotifyFinishEvent;
import com.ivan.stu.notetool.model.NotifyToRefreshNoteEvent;
import com.ivan.stu.notetool.network.api.SafeApiManager;
import com.ivan.stu.notetool.network.intercepter.NetworkTransformer;
import com.ivan.stu.notetool.network.postbody.GetNoteSubjectPostBody;
import com.ivan.stu.notetool.network.postbody.NotePostBody;
import com.ivan.stu.notetool.network.response.MySubjectResponse;
import com.ivan.stu.notetool.network.response.OperateNoteResponse;
import com.ivan.stu.notetool.network.response.Response;
import com.ivan.stu.notetool.utils.ActivityCollectorUtils;
import com.ivan.stu.notetool.utils.ConstrantManager;
import com.ivan.stu.notetool.utils.DateUtils;
import com.ivan.stu.notetool.utils.DeviceUtils;
import com.ivan.stu.notetool.utils.EditTextUtil;
import com.ivan.stu.notetool.utils.FileManager;
import com.ivan.stu.notetool.utils.ImageUtil;
import com.ivan.stu.notetool.utils.LookPicture;
import com.ivan.stu.notetool.utils.NetworkUtil;
import com.ivan.stu.notetool.utils.NoteToolManager;
import com.ivan.stu.notetool.utils.OkHttpUtils;
import com.ivan.stu.notetool.utils.ScreenUtil;
import com.ivan.stu.notetool.utils.SoftInputUtil;
import com.ivan.stu.notetool.utils.TextViewUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.observers.ResourceObserver;

import static com.blankj.utilcode.util.ScreenUtils.getScreenHeight;
import static com.blankj.utilcode.util.ScreenUtils.getScreenWidth;

public class AddNoteActivity extends AppCompatActivity implements View.OnClickListener{
    private ImageView iv_left_back,iv_subject_right;
    private TextView tv_save_note,tv_photo;
    private EditText et_titile,et_content;
    private TextView tv_choose_subject;
    private String mNoteTitle = "";
    private String mNoteContent = "";
    private String mCurrentSysID = "";
    private String mCurrentSysName = "";
    private Handler mHandler= new Handler();
    private List<MySubjectBean> subjectList = new ArrayList<>();
    private NoteSubjectAdapter noteSubjectAdapter;
    private PopupWindow popClass;
    private ListView listview;
    private boolean isExpendClass = false;
    private String subjectName = "英语";
    private String subjectId = "S2-English";
    private int mFirstSubLocation = 0;
    private TextView tv_text_length;
    private String url = "http://192.168.3.158:1314/api/V2/NoteTool/UploadImg";  //端扣号暂时改为1214
    private List<String> mImageList = new ArrayList<>();
    private List<Integer> mImageIndexs = new ArrayList<>();
    private Loading_view view ;
    private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "mms";
    private File photo_file = new File(path);
    private String photoPath = null;
    private int screenWidth;
    private NestedScrollView scrollView;
    public static int REQ_IMAGE_EDIT = 2;
    private File currentFile = null;
    private File imageEditedFile = null;
    private boolean isMatter = false;
    private int IsKeyPosint = 0;
    private RadioGroup radioGroup;
    private PopupWindow mSoftKeyboardTopPopupWindow;
    private boolean mIsSoftKeyBoardShowing = false;
    private ViewGroup mContainer;
    private Handler handler = new Handler();
    private ImageView iv_highlight_star;
    private LoadDialog mLoadDialog;
    private long firstTime;
    private TextView tv_source;

    private boolean isSaveed = false;

    private boolean isKeyChange =false;
    private boolean isTitleChange = false;
    private boolean isContentChange = false;
    private boolean isShowKeyBoard = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setDesignStyle(AddNoteActivity.this);
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        setContentView(R.layout.activity_add_note);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();

     /*   if (ConstrantManager.schoolLevel.equals("S2")){

            subjectId = "S2-English";

        }else {

            subjectId = "S1-English";
        }*/

        initSubjectID();
        initSystemID();
        findViews();
        initImageList();

        ActivityCollectorUtils.addActivity(AddNoteActivity.this,AddNoteActivity.class);
     //   getNoteSubjectList();  //系统集成没有学科筛选
        ///    ActivityCollectorUtils.addActivity(this);

        if (!EventBus.getDefault().isRegistered(this)) {

            EventBus.getDefault().register(this);

        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void notifyFinish(NotifyFinishEvent event){

        if (event.getFinishSigin() == 1){

            if (!isSaveed){

                if (mNoteTitle.equals("")){

                    mNoteTitle = DateUtils.getNowDate();

                }

                addNote(false);  //异常保存
            }

            finish();
        }
    }

    private void initSubjectID() {

        subjectId = ConstrantManager.currentNoteSubjectID;
        subjectName = ConstrantManager.currnetNoteSubject;

    }


    private void setDesignStyle(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            ViewGroup decorView = (ViewGroup) window.getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    private void initSystemID() {

        mCurrentSysID = ConstrantManager.currentSystemid;
        mCurrentSysName = ConstrantManager.currentSystemName;
     /*   switch (ConstrantManager.NOTE_CURRENT_PAGE){

            case 0:

                mCurrentSysID = "S21";
                mCurrentSysName = "小管家系统";
                break;

            case 1:

                mCurrentSysID = "630";
                mCurrentSysName = "课前预习系统";
                break;

            case 2:

                mCurrentSysID = "B10";
                mCurrentSysName = "课堂系统";
                break;

            case 3:

                mCurrentSysID = "510";
                mCurrentSysName = "课后作业系统";

                break;
            case 4:

                mCurrentSysID = "620";
                mCurrentSysName = "自由学习系统";

                break;
            case 5:

                mCurrentSysID = "S21";
                mCurrentSysName = "小管家系统";

                break;
            default:
                break;
        }*/

    }



    private void findViews() {

        mContainer = findViewById(R.id.ll_container);
        iv_highlight_star = findViewById(R.id.iv_highlight_star);

        tv_photo = findViewById(R.id.tv_photo);
        tv_choose_subject = findViewById(R.id.tv_choose_subject);
        et_content = findViewById(R.id.ed_note_content);
        et_titile = findViewById(R.id.ed_note_title);
        iv_left_back = (ImageView) findViewById(R.id.iv_left_back);
        tv_save_note = (TextView) findViewById(R.id.tv_save_note);
        tv_source = findViewById(R.id.tv_source);

        if (ConstrantManager.currentResourceName.length()>20){

            tv_source.setText(ConstrantManager.currentResourceName.substring(0,17)+"...");
        }else {

            tv_source.setText(ConstrantManager.currentResourceName);
        }

    //    tv_source.setOnClickListener(this);
        iv_left_back.setOnClickListener(this);
        tv_save_note.setOnClickListener(this);
   //     tv_choose_subject.setOnClickListener(this);   //系统集成不支持学科筛选
        tv_photo.setOnClickListener(this);
        et_content.setOnClickListener(this);
        et_titile.setOnClickListener(this);

        iv_highlight_star.setOnClickListener(this);
        iv_subject_right = findViewById(R.id.iv_subject_right);
        iv_subject_right.setVisibility(View.INVISIBLE);  //系统集成不支持学科筛选

        tv_choose_subject.setText(ConstrantManager.currnetNoteSubject);  //学科显示系统传进来的学科名称

        EditTextUtil.setEditTextInputSpace(AddNoteActivity.this,et_titile,0);
        EditTextUtil.setEditTextInputSpace(AddNoteActivity.this,et_content,1);

        et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                mNoteContent = charSequence.toString();

                if (isShowKeyBoard){

                    //            Log.e("输入字符",charSequence.toString().trim()+"");

                    //         if (!charSequence.toString().trim().equals("")){

                    isContentChange = true;

                    //                Log.e("isTitleChange",isTitleChange+"");
                    //             }
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

                mNoteContent = editable.toString();

            }
        });

        et_content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                Rect rect = new Rect();
                // 获取当前页面窗口的显示范围
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                int screenHeight = getScreenHeight();
                int keyboardHeight = screenHeight - rect.bottom; // 输入法的高度
                boolean preShowing = mIsSoftKeyBoardShowing;
                if (Math.abs(keyboardHeight) > screenHeight / 5) {


                    mIsSoftKeyBoardShowing = true; // 超过屏幕五分之一则表示弹出了输入法
                    Log.e("屏幕高度是", ScreenUtils.getScreenHeight()+"");

                    showKeyboardTopPopupWindow(getScreenWidth() / 2, keyboardHeight);

                }else {

                    if (preShowing) {
                        closePopupWindow();
                    }

                    mIsSoftKeyBoardShowing = false;
                }

            }
        });


        et_titile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                mNoteTitle = charSequence.toString();

                if (isShowKeyBoard){

                    //            Log.e("输入字符",charSequence.toString().trim()+"");

                    //         if (!charSequence.toString().trim().equals("")){

                    isTitleChange = true;

                    //                Log.e("isTitleChange",isTitleChange+"");
                    //             }
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mNoteTitle = editable.toString();
            }
        });

        mLoadDialog = new LoadDialog.Builder(AddNoteActivity.this).setMsg("正在上传..").setCancelable(false).build();

    }

    private void closePopupWindow() {
        if (mSoftKeyboardTopPopupWindow != null && mSoftKeyboardTopPopupWindow.isShowing()) {
            mSoftKeyboardTopPopupWindow.dismiss();
            mSoftKeyboardTopPopupWindow = null;
        }
    }

    private void showKeyboardTopPopupWindow(int x, int y) {

        isShowKeyBoard = true;

        if (mSoftKeyboardTopPopupWindow != null && mSoftKeyboardTopPopupWindow.isShowing()) {
            updateKeyboardTopPopupWindow(x, y); //可能是输入法切换了输入模式，高度会变化（比如切换为语音输入）
            return;
        }

        View popupView = getLayoutInflater().inflate(R.layout.soft_keyboard_top_tool_view, null);
        popupView.findViewById(R.id.tv_clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!et_content.getText().toString().trim().equals("")){

                    TextViewUtils.showDialog(AddNoteActivity.this, "您确定要清空所有笔记内容吗？", new PositiveCallBack() {
                        @Override
                        public void positiveCallBack(AlertDialog dialog) {

                            if (dialog!=null){

                                dialog.dismiss();
                            }

                            et_content.setText("");

                        }
                    }, new NegativeCallBack() {
                        @Override
                        public void negativeCallBack(AlertDialog dialog) {

                            if (dialog!=null){

                                dialog.dismiss();
                            }
                        }
                    });
                }
            }
        });

        radioGroup = popupView.findViewById(R.id.radioGroup);

        if (ConstrantManager.currentSystemid.equals("b30") || ConstrantManager.currentSystemid.equals("B30")){

            radioGroup.findViewById(R.id.rb_camera).setVisibility(View.GONE);

        }else {

            radioGroup.findViewById(R.id.rb_camera).setVisibility(View.VISIBLE);

        }

    /*    LinearLayout.LayoutParams params;
        if (ScreenUtil.getScreenWidth(AddNoteActivity.this)>720){

             params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,70);

        }else {

             params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,50);
        }
        params.gravity = Gravity.CENTER_VERTICAL;
        radioGroup.setLayoutParams(params);*/



        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                RadioButton radioButton = radioGroup.findViewById(i);
                int id = radioButton.getId();
                if (id == R.id.rb_camera){


                    verifyPermissions(AddNoteActivity.this,100);

                //    openCamera();

                }else if (id == R.id.rb_picture){



                    verifyPermissions(AddNoteActivity.this,200);




                }else {

                    verifyPermissions(AddNoteActivity.this,300);

                }
            }
        });

        mSoftKeyboardTopPopupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, 80, true);
       // mSoftKeyboardTopPopupWindow = new PopupWindow(popupView);
        mSoftKeyboardTopPopupWindow.setTouchable(true);
        mSoftKeyboardTopPopupWindow.setOutsideTouchable(false);
        mSoftKeyboardTopPopupWindow.setFocusable(false);
        mSoftKeyboardTopPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); //解决遮盖输入法
        mSoftKeyboardTopPopupWindow.showAtLocation(mContainer, Gravity.BOTTOM, x, y);
    }



    public void openCamera( ) {
        //獲取系統版本
        int currentapiVersion = Build.VERSION.SDK_INT;

        Log.e("当前系统版本",currentapiVersion+"");
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            if (!photo_file.exists()) {

                photo_file.mkdirs();
            }

            try {

                String temp = DateUtils.dateToStamp(DateUtils.getNowDate());
                photo_file = new File(path, "/"+temp+".jpg");

                if (photo_file != null) {

                    Uri imageUri;
                    if (currentapiVersion < 24) {

                        Log.e("走的这","小于7.0");
                        // 从文件中创建uri
                        imageUri = Uri.fromFile(photo_file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    } else {

                        Log.e("走的这","大于7.0");
                        //兼容android7.0 使用共享文件的形式
                        ContentValues contentValues = new ContentValues(1);
                        contentValues.put(MediaStore.Images.Media.DATA, photo_file.getAbsolutePath());
                        //检查是否有存储权限，以免崩溃
                        if (ContextCompat.checkSelfPermission(AddNoteActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED) {
                            //申请WRITE_EXTERNAL_STORAGE权限
                            Toast.makeText(AddNoteActivity.this,"请开启存储权限",Toast.LENGTH_SHORT).show();
                            return ;
                        }
                        imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

                    }

                    // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA

                    if (ContextCompat.checkSelfPermission(AddNoteActivity.this, Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED){

                        ActivityCompat.requestPermissions(AddNoteActivity.this, new String[]{
                                Manifest.permission.CAMERA}, 400);

                    }else {

                        startActivityForResult(intent, 1);
                    }
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {

            Log.e("aaaaaaaaaaa","没有sd卡");
        }
    }

    public void verifyPermissions(Activity activity,int requestCode) {

        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                ) {
            //     Toast.makeText(this, "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();

            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(activity, new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
        } else {  //已授权

            if (requestCode == 100){

                openCamera();

            }else if (requestCode == 200){

                openAblum();

            }else if (requestCode == 300){

                openPanel();

            }else {


            }


        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:

                Toast.makeText(this, "code"+grantResults[0], Toast.LENGTH_SHORT).show();

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.e("aaaaaaaaaaaa","授权成功！！！！");

                    openCamera();

                } else {
                    // 没有获取到权限，做特殊处理

                    Toast.makeText(this, "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();

                }
                break;
            case 200:

                Toast.makeText(this, "code"+grantResults[0], Toast.LENGTH_SHORT).show();

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.e("aaaaaaaaaaaa","授权成功！！！！");

                    openAblum();

                } else {
                    // 没有获取到权限，做特殊处理

                    Toast.makeText(this, "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();

                }


                break;
            case 300:

                Toast.makeText(this, "code"+grantResults[0], Toast.LENGTH_SHORT).show();

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.e("aaaaaaaaaaaa","授权成功！！！！");

                    openPanel();

                } else {
                    // 没有获取到权限，做特殊处理

                    Toast.makeText(this, "没有获取权限,请手动开启权限", Toast.LENGTH_SHORT).show();

                }

                break;
            case 400:

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED){

                    Log.e("aaaaaaaaaaa","开启相机权限已开启！");

                    openCamera();

                }else {

                    Log.e("aaaaaaaaaaa","开启相机权限被拒！");
                    Toast.makeText(this, "没有获取权限,请手动开启相机权限", Toast.LENGTH_SHORT).show();

                }

                break;
        }
    }

    private void openPanel() {

        try {

            String temp = DateUtils.dateToStamp(DateUtils.getNowDate());
            FileManager.init(AddNoteActivity.this,ConstrantManager.FILE_MANAGER_ROOT);
            imageEditedFile = FileManager.getFile(FileManager.getRootDir(),temp+".jpg");
            IMGEditActivity.openEditor(AddNoteActivity.this,null,imageEditedFile.getAbsolutePath());  //打开手写画板

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    private void openAblum() {

        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 0);

    }

    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    private void updateKeyboardTopPopupWindow(int x, int y) {
        if (mSoftKeyboardTopPopupWindow != null && mSoftKeyboardTopPopupWindow.isShowing()) {
            mSoftKeyboardTopPopupWindow.update(x, y, mSoftKeyboardTopPopupWindow.getWidth(), mSoftKeyboardTopPopupWindow.getHeight());
        }
    }

    private void initImageList() {

        mImageList.clear();
        mImageIndexs.clear();

        //input是获取将被解析的字符串
        String input = et_content.getText().toString();
        Pattern p = Pattern.compile("<img.*?>");
        Matcher m = p.matcher(input);

        while (m.find()) {

            String s = m.group();
            final int start = m.start();
            final int end = m.end();
            Pattern p_src = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)");
            Matcher m_src = p_src.matcher(s);
            String path = "";
            if (m_src.find()) {

                String src = m_src.group().split("=")[1];
                path = src.substring(1, src.length() - 1);

            }
            //按图片在文中的顺序存储
            mImageList.add(path);
            mImageIndexs.add(start);
        }

    }

    private void addNote(final boolean isNormal){

        NotePostBody postBody = new NotePostBody();
        postBody.setSystemID(mCurrentSysID);//由集成系统传进来的系统ID
        postBody.setSystemName(mCurrentSysName);//由集成系统传进来的系统名称
        postBody.setUserID(ConstrantManager.childUserID);
        postBody.setUserName(ConstrantManager.childUserName);
        postBody.setNoteContent(mNoteContent);
        postBody.setNoteTitle(mNoteTitle);
        postBody.setOperateFlag(1);
        postBody.setSubjectID(subjectId);  //由集成系统传进来的学科ID
        postBody.setSubjectName(subjectName); //由集成系统传进来的学科名字
        postBody.setSchoolID(ConstrantManager.childSchoolID);
        postBody.setResourceName(ConstrantManager.currentResourceName);//这里要传系统传进来的资源名称
        postBody.setResourceID(ConstrantManager.currentResourceID);   //这里要传系统传进来的资源ID

        if (ConstrantManager.MaterialID.equals("")){

            postBody.setMaterialID(ConstrantManager.currentResourceID);  //集成系统传进来id，用于生成跳转连接。

        }else {

            postBody.setMaterialID(ConstrantManager.MaterialID);  //集成系统传进来id，用于生成跳转连接。
        }

        postBody.setMaterialIndex(-1);  //课后作业专用 暂时用不到
        postBody.setIsKeyPoint(IsKeyPosint);


        SafeApiManager.getTestApi(3).addNote(postBody)
                .compose(NetworkTransformer.<OperateNoteResponse>commonSchedulers())
                .subscribe(new ResourceObserver<OperateNoteResponse>() {
                    @Override
                    public void onNext(OperateNoteResponse operateNoteResponse) {

                        if (operateNoteResponse.ErrorCode.substring(operateNoteResponse.ErrorCode.length()-2,operateNoteResponse.ErrorCode.length()).equals("00")){


                            if (isNormal){

                                isSaveed = true;

                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {

                                        NotifyToRefreshNoteEvent event = new NotifyToRefreshNoteEvent();
                                        event.setResult(1);
                                        EventBus.getDefault().post(event);
                                        if (mLoadDialog!=null){
                                            mLoadDialog.dismiss();
                                        }

                                        TextViewUtils.showToast(AddNoteActivity.this,2,"创建笔记成功！");
                                        finish();
                                    }
                                },1000);
                            }



                        }else {

                            if (mLoadDialog!=null){
                                mLoadDialog.dismiss();
                            }

                            TextViewUtils.showToast(AddNoteActivity.this,0,"添加笔记失败，请重试！");

                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                        TextViewUtils.showToast(AddNoteActivity.this,0,"接口访问失败，请检查网络环境后重试！");

                        if (mLoadDialog!=null){
                            mLoadDialog.dismiss();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void showPopClass(){
        View popView= LayoutInflater.from(AddNoteActivity.this).inflate(R.layout.pop_class_drop_list,null);
        if(popClass ==null){
            popClass = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popClass.setFocusable(true);
            popClass.setOutsideTouchable(true);
            popClass.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            popClass.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {


                    isExpendClass=false;
                    iv_subject_right.setRotation(0);

                }
            });
        }
        popClass.showAsDropDown(tv_choose_subject,0, DeviceUtils.dip2px(AddNoteActivity.this,10));
        if(noteSubjectAdapter==null){
            listview = (ListView) popView.findViewById(R.id.listview);
            if(subjectList.size()<5){
                ViewGroup.LayoutParams layoutParams = listview.getLayoutParams();
                layoutParams.height= DeviceUtils.dip2px(AddNoteActivity.this,40)*subjectList.size();
                listview.setLayoutParams(layoutParams);
            }
            noteSubjectAdapter = new NoteSubjectAdapter(AddNoteActivity.this,subjectList);
            noteSubjectAdapter.setCurrentCheckIndex(mFirstSubLocation);
            listview.setAdapter(noteSubjectAdapter);
            popView.findViewById(R.id.view_mark).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if(popClass!=null&&popClass.isShowing()){
                        popClass.dismiss();

                    }
                }
            });
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    noteSubjectAdapter.setCurrentCheckIndex(position);
                    noteSubjectAdapter.notifyDataSetChanged();
                    popClass.dismiss();
                    tv_choose_subject.setText(subjectList.get(position).getSubjectName());
                    subjectName=subjectList.get(position).getSubjectName();
                    subjectId=subjectList.get(position).getSubjectID();

                }
            });
        }else{

            noteSubjectAdapter.notifyDataSetChanged();
        }

    }

    private void getNoteSubjectList(){

        GetNoteSubjectPostBody body  = new GetNoteSubjectPostBody();

        body.setBackUpOne("");
        body.setBackUpTwo("");
        body.setSchoolID(ConstrantManager.childSchoolID);
        body.setToken(ConstrantManager.Token);
        body.setBackUpOne("");
        body.setUserID(ConstrantManager.childUserID);
        body.setUserType(ConstrantManager.userType);

        SafeApiManager.getTestApi(3).getNoteSubjectList(body)
                .compose(NetworkTransformer.<MySubjectResponse>commonSchedulers())
                .subscribe(new ResourceObserver<MySubjectResponse>() {
                    @Override
                    public void onNext(MySubjectResponse mySubjectResponse) {

                        if (mySubjectResponse.Result!=null&&mySubjectResponse.Result.size()>0){

                            subjectList.clear();

                            subjectList.addAll(mySubjectResponse.Result);

                            for (int i = 0;i<subjectList.size();i++){

                                if (subjectList.get(i).getSubjectName().equals("英语")){

                                    mFirstSubLocation = i;
                                    subjectId = subjectList.get(i).getSubjectID();  //一开始默认选中为英语
                                }
                            }
                        }else {

                            TextViewUtils.showToast(AddNoteActivity.this,0,mySubjectResponse.Reason);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                        TextViewUtils.showToast(AddNoteActivity.this,0,e.toString());

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {

            case 0:  //相册
                if (resultCode == RESULT_OK) {

                    final Uri uri = data.getData();
                    String[] pojo = {MediaStore.Images.Media.DATA};
                    Cursor cursor = managedQuery(uri, pojo, null, null, null);
                    if (cursor != null) {

                        int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        cursor.moveToFirst();
                        String path = cursor.getString(colunm_index);
                        final File file = new File(path);
                        currentFile = file;

                        String temp = null;
                        try {
                            temp = DateUtils.dateToStamp(DateUtils.getNowDate());
                            FileManager.init(AddNoteActivity.this,ConstrantManager.FILE_MANAGER_ROOT);
                            imageEditedFile = FileManager.getFile(FileManager.getRootDir(),temp+".jpg");
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        IMGEditActivity.openEditor(AddNoteActivity.this,currentFile.getAbsolutePath(),imageEditedFile.getAbsolutePath());
                    }
                }
                break;

            case 1:  //拍照
                if (resultCode == RESULT_OK) {

                    if (photo_file.exists()){

                        //发送广播通知系统相册更新缩略图 ，该方法的兼容性有待测试，目前有效

                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(photo_file)));
                        currentFile = photo_file;
                        String temp = null;
                        try {
                            temp = DateUtils.dateToStamp(DateUtils.getNowDate());
                            FileManager.init(AddNoteActivity.this,ConstrantManager.FILE_MANAGER_ROOT);
                            imageEditedFile = FileManager.getFile(FileManager.getRootDir(),temp+".jpg");
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        IMGEditActivity.openEditor(AddNoteActivity.this,currentFile.getAbsolutePath(),imageEditedFile.getAbsolutePath());  //这里需要改变图片编辑后的存储路径，不然会覆盖原图。
                    }
                }
                break;

            case 2:

                //从文件读出编辑过的图片并展示

                if (resultCode == RESULT_OK){

                    if (imageEditedFile!=null && imageEditedFile.exists()){

                        TextViewUtils.showProgressDialog(AddNoteActivity.this,AddNoteActivity.class,"图片上传中...");
                        OkHttpUtils.getInstance().upImage(AddNoteActivity.this, imageEditedFile, new EditNoteActivity.HttpCallBack() {
                            @Override
                            public void onSuccess(String result) {
                                Gson gson = new Gson();
                                Response response = gson.fromJson(result, Response.class);

                                if (response.getResult()!=null&&response.getResult().size()>0){

                                    //手机系统大于7.0的话uri的获取需要用到fileprovider

                                    //在大屏幕的情况下要重新设置图片的宽高，或者在加载图片时不进行override

                                    ImageUtil.showBitMap(AddNoteActivity.this,Uri.fromFile(imageEditedFile),response.getResult().get(0),et_content,screenWidth);
                                    TextViewUtils.hideProgressDialog(AddNoteActivity.this);
                                    TextViewUtils.showToast(AddNoteActivity.this,2,response.getReason());

                                }else {

                                    TextViewUtils.hideProgressDialog(AddNoteActivity.this);
                                    TextViewUtils.showToast(AddNoteActivity.this,0,response.getReason());
                                }
                            }

                            @Override
                            public void onFailure(String error) {

                                TextViewUtils.hideProgressDialog(AddNoteActivity.this);
                                TextViewUtils.showToast(AddNoteActivity.this,0,error);

                            }
                        });
                    }
                }
                break;
        }
    }



    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @SuppressLint("ResourceAsColor")
    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.iv_left_back) {//   finish();

            if (et_content.getText().toString().trim().equals("")){

                finish();

            }else {

                if (isContentChange||isTitleChange||isKeyChange){

                    TextViewUtils.showDialog(AddNoteActivity.this, "修改的内容未保存，您确定要退出吗？", new PositiveCallBack() {
                        @Override
                        public void positiveCallBack(AlertDialog dialog) {

                    /*    if (mLoadDialog != null) {

                            mLoadDialog.setMsg("正在保存..");
                            mLoadDialog.show();
                        }

                        //创建笔记
                        saveNote();
                        dialog.dismiss();*/

                            dialog.dismiss();
                            finish();

                        }
                    }, new NegativeCallBack() {
                        @Override
                        public void negativeCallBack(AlertDialog dialog) {

                            dialog.dismiss();
                            //   finish();
                        }
                    });
                }else {

                    finish();
                }

            }


        } else if (i == R.id.tv_save_note) {

            saveNote();

        } else if (i == R.id.tv_choose_subject) {//选择学科
            iv_subject_right.setRotation(180);
            showPopClass();
            //    PopupWindowManager.showPopClass(AddNoteActivity.this,tv_choose_subject,subjectList,mFirstSubLocation,this);
            SoftInputUtil.hideSystemKeyBoard(AddNoteActivity.this, tv_save_note);


        } else if (i == R.id.ed_note_content) {

            SoftInputUtil.showSoftInput(AddNoteActivity.this,tv_save_note);
            initImageList();  //更新图片的路径集合和索引集合
            handleImageClick();  //处理图片的点击事件

        } else if (i == R.id.iv_highlight_star) {

            isKeyChange = true;

            if (IsKeyPosint != 1) {  //标记为重点

                iv_highlight_star.setBackground(getResources().getDrawable(R.mipmap.notetool_highlight_star));
                IsKeyPosint = 1;
                TextViewUtils.showToast(AddNoteActivity.this, 2, "已标记为重点");

            } else { //取消重点标记

                iv_highlight_star.setBackground(getResources().getDrawable(R.mipmap.notetool_highlight_star_unselet));
                IsKeyPosint = 0;
                TextViewUtils.showToast(AddNoteActivity.this, 2, "已取消标记");

            }

        } else if (i == R.id.tv_source){



        }else if (i == R.id.ed_note_title){

            SoftInputUtil.showSoftInput(AddNoteActivity.this,tv_save_note);

        }
    }


    private void saveNote() {

        if (mNoteTitle.equals("")){

            mNoteTitle = DateUtils.getNowDate();

        }

        if (mNoteContent.equals("")){

            TextViewUtils.showToast(AddNoteActivity.this,1,"输入的内容不能为空！");
            mLoadDialog.dismiss();

        }else {

            mLoadDialog.show();
            addNote(true);

    /*        if (NetworkUtil.hasNetwork(AddNoteActivity.this)){
                mLoadDialog.show();
                addNote();

            }else {

                TextViewUtils.showToast(AddNoteActivity.this,1,"请连接网络再试！");
                mLoadDialog.dismiss();

            }*/
        }

    }

    private void handleImageClick() {

        Spanned s = et_content.getText();
        ImageSpan[] imagespans = s.getSpans(0, s.length(), ImageSpan.class);

        Log.e("当前共有span",imagespans.length+"");

        int selectStart = et_content.getSelectionStart();
        for (int i =0;i<imagespans.length;i++){

            int start = s.getSpanStart(imagespans[i]);
            int end = s.getSpanEnd(imagespans[i]);
            if (selectStart >= start && selectStart <= end){  //说明点击的是图片
                Log.e("sub",s.subSequence(start,end).toString());
                et_content.setSelection(end);  //将光标定位到图片的末尾，即下一行
                for (int j = 0;j<mImageIndexs.size();j++){
                    Log.e("index",mImageIndexs.get(j)+"=="+start);
                    if (mImageIndexs.get(j) == start){

                        Log.e("点击第",j+"张图片");

                        LookPicture.look(mImageList, j, AddNoteActivity.this, new LookPicture.ImageDownLoadCallBack() {
                            @Override
                            public void onCompleted(String localPath) {

                            }

                            @Override
                            public void onError(String error) {

                            }

                            @Override
                            public void onFileOpened(String localPath) {

                            }
                        });

                        SoftInputUtil.hideSystemKeyBoard(AddNoteActivity.this,tv_save_note);

                    }

                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TextViewUtils.clearProgressDialog();

        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            // long firstTime = 0;
            if (secondTime - firstTime > 2000) {

                if (et_content.getText().toString().trim().equals("")){

                    finish();

                }else {


                    if (isKeyChange||isTitleChange||isContentChange){

                        TextViewUtils.showDialog(AddNoteActivity.this, "修改的内容未保存，您确定要退出吗？", new PositiveCallBack() {
                            @Override
                            public void positiveCallBack(AlertDialog dialog) {

                   /*         if (mLoadDialog!=null){

                                mLoadDialog.setMsg("正在保存..");
                                mLoadDialog.show();
                            }

                            //创建笔记
                            saveNote();
                            dialog.dismiss();*/

                                dialog.dismiss();
                                finish();

                            }
                        }, new NegativeCallBack() {
                            @Override
                            public void negativeCallBack(AlertDialog dialog) {

                                dialog.dismiss();
                                //     finish();
                            }
                        });
                    }else {

                        finish();
                    }
                }


                firstTime = secondTime;
                return true;

            } else{

            }
        }
        return super.onKeyDown(keyCode, event);
    }

}
